package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.Dlhlsepsensor;
import com.example.onlinemonitoring.model.Dlhlsephistory;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Dlhlsensor;
import com.example.onlinemonitoring.serviceImpl.DlhlsepsensorServiceImpl;
import com.example.onlinemonitoring.dao.DlhlsepsensorMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;
import com.example.onlinemonitoring.Util.CRC16;
import java.text.ParseException;
import java.util.Date;
import java.net.InetSocketAddress;
import java.net.Socket;
import tk.mybatis.mapper.entity.Example;
/*这里beanName需要和数据库Appdevice中的simple对应并加上Com,不对应请自行修改
    例:simple:dlhl
    @Service("dlhlCom")
*/
@Service("dlhlsepCom")
@Scope("prototype")
public class DlhlsepCom extends CommPortManager {
        @Autowired
        private DlhlsepsensorServiceImpl dlhlsepsensorServiceImpl;
        @Autowired
        DlhlsepsensorMapper dlmapper;
        //float  dc=0;
        private float  dc[] = new float[255];
        int SignalPower = 0;
        int addrid =0;
        Socket skdl;
        @Override
        public void receiveData(String str) {
            try {
                String ipstr = "";
                int clientport =0;
                if (ad.getCommunicationmode() == 3)
                {
                    skdl=sclsocket;
                    InetSocketAddress socketAddress = (InetSocketAddress) skdl.getRemoteSocketAddress();
                    String clientIpAddress = socketAddress.getAddress().getHostAddress();
                    clientport = socketAddress.getPort();
                    ipstr = clientIpAddress;
    
                }


                str = str.toUpperCase();
                //"7E01804000080001000200030005CHKSUM"
                setText(str);

                if(str.length()==4)
                {
                                   

                    SignalPower = (Integer.valueOf(str.substring(0, 2))-30)*10+ Integer.valueOf(str.substring(2, 4))-30;   
                    if (ad.getCommunicationmode() == 3)
                    {
                        Dlhlsepsensor dldy = new Dlhlsepsensor();
                        dldy.setStationid(ad.getStationid());
                        dldy.setDevicegroup(ad.getDevicegroup());
                        //dldy.setDeviceaddr(addrint);
                        dldy.setIpaddr(ipstr);
                        dldy.setPort(clientport);
                        //dldy.setLastalarmlevel(0);
                        //dldy.setLastalarmmessage("");
                        dldy.setLastsignalpower(SignalPower);
                        dldy.setLastcommunicationstatus(0);
                        dldy.setLastdatatime(new Date());
    
                        Example example1 = new Example(Dlhlsepsensor.class);
                        Example.Criteria criteria1 = example1.createCriteria();
                        criteria1.andEqualTo("stationid", 1);
                        criteria1.andEqualTo("devicegroup", dldy.getDevicegroup());
                        //criteria1.andEqualTo("deviceaddr", dldy.getDeviceaddr());
                        criteria1.andEqualTo("ipaddr", ipstr);
                        //criteria1.andEqualTo("port", clientport);
    
                        int ret = dlhlsepsensorServiceImpl.updateByExampleSelective(dldy,example1);
                        if (ret < 1) {
                            setText("当前数据库无监测点：设备地址" + ipstr);
                        }
                    }
                    else if(ad.getCommunicationmode() == 2)
                    {

                    }

                    return;                 
                }
                if ("7F".equals(str.substring(0, 2))==false) {
                    return;
                }
               

                //地址解析addr
                String addrstr = str.substring(2, 4);
                //转地址
                Integer addrint = parseHex4(addrstr);

                Dlhlsepsensor dlsensor = new Dlhlsepsensor();
                //设置设备地址
                dlsensor.setStationid(ad.getStationid());
                dlsensor.setDevicegroup(ad.getDevicegroup());
                dlsensor.setDeviceaddr(addrint);
                dlsensor.setIpaddr(ipstr);
                dlsensor.setPort(clientport);
                dlsensor.setLastalarmlevel(0);
                dlsensor.setLastalarmmessage("");
                dlsensor.setLastcommunicationstatus(0);
                dlsensor.setLastdatatime(new Date());
                if ( dlhlsepsensorServiceImpl.Update(dlsensor, false) == 0) {
                    setText("更新实时数据失败，请检查数据库连接");
                }

                reSend[addrint] = 0;
               
                // dlhlserviceimpl.setstatus(0,addrint);
                reSend[parseHex4(addrstr)] = 0;
                //设备类型编码
                String s_cid1 = str.substring(4, 6);
                String s_cid2 = str.substring(6, 8);
                //请求返回状态00(正常）01 CHKSUM错
                String rtn = str.substring(8, 10);
                Integer startIndex = 12;
                //判断请求返回，是否电流相关，返回码是否正常
                if ( "41".equals(s_cid2)) {
                    setText("设备返回数据： 站点号：" + ad.getStationid() + " 设备组：" + ad.getDevicegroup() + " 设备地址：" + addrint);
                    //String length = str.substring(12, 14);

                    Dlhlsepsensor dlhlsensor = new Dlhlsepsensor();
                    //设置设备地址
                    dlhlsensor.setStationid(ad.getStationid());
                    dlhlsensor.setDevicegroup(ad.getDevicegroup());
                    dlhlsensor.setDeviceaddr(addrint);
                    //查询对象
                    Dlhlsepsensor record = dlhlsepsensorServiceImpl.getModel(dlhlsensor);
                    if (record == null) {
                        setText("当前数据库无监测点：设备地址" + addrint);
                    }
                    //    String stlyestr = record.getStyle();
                    //    if((stlyestr==null)||(stlyestr.equals("")))
                    //    {
                    //        stlyestr="acurrent|1|A相电流,bcurrent|1|B相电流,ccurrent|1|C相电流,dcurrent|1|负荷电流";
                    //        record.setStyle(stlyestr);
                    //    }
                    //获取电流系数
                    float agreatevalue = record.getAcurrentcoefficientgreatevalue() == null ? 1f : record.getAcurrentcoefficientgreatevalue();
                    float bgreatevalue = record.getBcurrentcoefficientgreatevalue() == null ? 1f : record.getBcurrentcoefficientgreatevalue();
                    float cgreatevalue = record.getCcurrentcoefficientgreatevalue() == null ? 1f : record.getCcurrentcoefficientgreatevalue();
                    //float a1greatevalue = record.getA1currentcoefficientgreatevalue() == null ? 1f : record.getA1currentcoefficientgreatevalue();
                    //float b1greatevalue = record.getB1currentcoefficientgreatevalue() == null ? 1f : record.getB1currentcoefficientgreatevalue();
                    //float c1greatevalue = record.getC1currentcoefficientgreatevalue() == null ? 1f : record.getC1currentcoefficientgreatevalue();
                    float dgreatevalue = record.getDcurrentcoefficientgreatevalue() == null ? 1f : record.getDcurrentcoefficientgreatevalue();
                    //float ggreatevalue = record.getGcurrentcoefficientgreatevalue() == null ? 1f : record.getGcurrentcoefficientgreatevalue();
                    float alessvalue = record.getAcurrentcoefficientlessvalue() == null ? 1f : record.getAcurrentcoefficientlessvalue();
                    float blessvalue = record.getBcurrentcoefficientlessvalue() == null ? 1f : record.getBcurrentcoefficientlessvalue();
                    float clessvalue = record.getCcurrentcoefficientlessvalue() == null ? 1f : record.getCcurrentcoefficientlessvalue();
                    //float a1lessvalue = record.getA1currentcoefficientlessvalue() == null ? 1f : record.getA1currentcoefficientlessvalue();
                    //float b1lessvalue = record.getB1currentcoefficientlessvalue() == null ? 1f : record.getB1currentcoefficientlessvalue();
                    //float c1lessvalue = record.getC1currentcoefficientlessvalue() == null ? 1f : record.getC1currentcoefficientlessvalue();
                    float dlessvalue = record.getDcurrentcoefficientlessvalue() == null ? 1f : record.getDcurrentcoefficientlessvalue();
                    //float glessvalue = record.getGcurrentcoefficientlessvalue() == null ? 1f : record.getGcurrentcoefficientlessvalue();

                    float lastacurrnet = Integer.parseInt(str.substring(startIndex, startIndex += 4), 16) / 100f;
                    float lastbcurrnet = Integer.parseInt(str.substring(startIndex, startIndex += 4), 16) / 100f;
                    float lastccurrnet = Integer.parseInt(str.substring(startIndex, startIndex += 4), 16) / 100f;
                    //float lastgcurrnet = Integer.parseInt(str.substring(startIndex, startIndex += 4), 16) / 100f;
                    float lastdcurrnet = Integer.parseInt(str.substring(startIndex, startIndex += 4), 16)/ 100f;
                    setText("信号强度:" + SignalPower );
                    setText("A相电流：" + lastacurrnet + "A" + " B相电流：" + lastbcurrnet + "A" + " C相电流：" + lastccurrnet+ "A" + " 负荷电流：" + lastdcurrnet + "A");
                    //setText("A相电流：" + lastacurrnet + "A" + " B相电流：" + lastbcurrnet + "A" + " C相电流：" + lastccurrnet+ "A" + " 接地电流：" + lastgcurrnet + "A"+ " 负荷电流：" + lastdcurrnet + "A");
                    //setText("A1相电流：" + lasta1currnet + "A" + " B1相电流：" + lastb1currnet + "A" + " C1相电流：" + lastc1currnet + "A" + " 负荷电流：" + lastd1currnet + "A");
                
                    //float lasta1currnet = Integer.parseInt(str.substring(startIndex, startIndex += 4), 16) / 100f;
                    //float lastb1currnet = Integer.parseInt(str.substring(startIndex, startIndex += 4), 16) / 100f;
                    //float lastc1currnet = Integer.parseInt(str.substring(startIndex, startIndex += 4), 16) / 100f;
                    //float lastd1currnet = Integer.parseInt(str.substring(startIndex, startIndex += 4), 16) / 100f;
                    dc[addrint] = lastdcurrnet;
                    int indexdcurrnetaddr = isnull(record.getLastdcurrentaddr());
                    lastdcurrnet = dc[indexdcurrnetaddr];

                    //母线电流随1号
                    // if(addrint == indexdcurrnetaddr){
                    //     dc = lastdcurrnet;
                    // }else{
                    //     lastdcurrnet = dc;
                    // }

                        // lastacurrnet = lastacurrnet-0.5f;
                        // lastbcurrnet = lastbcurrnet-0.5f;
                        // lastccurrnet = lastccurrnet-0.5f;
                    if (ad.getCommunicationmode() == 2)
                        dlhlsensor.setLastsignalpower(SignalPower);
                    //设置电流相关
                    dlhlsensor.setLastacurrent(getCurrent(lastacurrnet, agreatevalue, alessvalue));
                    dlhlsensor.setLastbcurrent(getCurrent(lastbcurrnet, bgreatevalue, blessvalue));
                    dlhlsensor.setLastccurrent(getCurrent(lastccurrnet, cgreatevalue, clessvalue));
                    dlhlsensor.setLastdcurrent(getDcurrent(lastdcurrnet, dgreatevalue, dlessvalue));
                    //dlhlsensor.setLastgcurrent(getCurrent(lastgcurrnet, ggreatevalue, glessvalue));
                    dlhlsensor.setLastacurrentratio(lastacurrnet);
                    dlhlsensor.setLastbcurrentratio(lastbcurrnet);
                    dlhlsensor.setLastccurrentratio(lastccurrnet);
                    dlhlsensor.setLastdcurrentratio(lastdcurrnet);
                    //dlhlsensor.setLastgcurrentratio(lastgcurrnet);
                    //    dlhlsensor.setLasta1current( getCurrent(lasta1currnet, a1greatevalue, a1lessvalue));
                    //    dlhlsensor.setLastb1current( getCurrent(lastb1currnet, b1greatevalue, b1lessvalue));
                    //    dlhlsensor.setLastc1current( getCurrent(lastc1currnet, c1greatevalue, c1lessvalue));
                    //    dlhlsensor.setLastd1current( getDcurrent(lastd1currnet, dgreatevalue, dlessvalue));
                    AddAndUpdate(record,dlhlsensor);
                } else {
                    setText("从设备返回的数据有误！请检查串口！");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                setText("从设备返回的数据有误！请检查串口！");
            }
        }

        @Transactional
        private void AddAndUpdate(Dlhlsepsensor record,Dlhlsepsensor dlhl) {
            int alarmLevel = 0;// 总报警等级
            String alarmMessage = "";// 报警消息
            //获取数据库中的报警值相关
            if (record.getCurrentalarmvlaue() == null ||
                    record.getCurrentalarmrelievevlaue() == null ||
                    record.getCurrentwarnvlaue() == null ||
                    record.getCurrentwarnrelievevlaue() == null ||
                    record.getCurrentpercentagealarmvlaue() == null ||
                    record.getCurrentpercentagealarmrelievevlaue() == null ||
                    record.getCurrentpercentagewarnvlaue() == null ||
                    record.getCurrentpercentagewarnrelievevlaue() == null ||
                    record.getCoefficientalarmvlaue() == null ||
                    record.getCoefficientalarmrelievevlaue() == null ||
                    record.getCoefficientwarnvlaue() == null ||
                    record.getCoefficientwarnrelievevlaue() == null
            ) {
                setText("设备地址" + record.getDeviceaddr() + " 未设置报警值！");
                return;
            }
            //电流报警值
            float currentalarmvlaue = record.getCurrentalarmvlaue();
            //电流报警解除值
            float currentalarmrelievevlaue = record.getCurrentalarmrelievevlaue();
            //电流预警值
            float currentwarnvlaue = record.getCurrentwarnvlaue();
            // 电流预警解除值
            float currentwarnrelievevlaue = record.getCurrentwarnrelievevlaue();
            // 电流比报警值
            float currentpercentagealarmvlaue = record.getCurrentpercentagealarmvlaue();
            // 电流比报警解除值
            float currentpercentagealarmrelievevlaue = record.getCurrentpercentagealarmrelievevlaue();
            // 电流比预警值
            float currentpercentagewarnvlaue = record.getCurrentpercentagewarnvlaue();
            // 电流比预警解除值
            float currentpercentagewarnrelievevlaue = record.getCurrentpercentagewarnrelievevlaue();
            // 不平衡系数报警值
            float coefficientalarmvlaue = record.getCoefficientalarmvlaue();
            // 不平衡系数报警解除值
            float coefficientalarmrelievevlaue = record.getCoefficientalarmrelievevlaue();
            // 不平衡系数预警值
            float coefficientwarnvlaue = record.getCoefficientwarnvlaue();
            // 不平衡系数预警解除值
            float coefficientwarnrelievevlaue = record.getCoefficientwarnrelievevlaue();
    
            //报警逻辑
            float lastacurrent = dlhl.getLastacurrent();
            float lastbcurrent = dlhl.getLastbcurrent();
            float lastccurrent = dlhl.getLastccurrent();
            float lastdcurrent = dlhl.getLastdcurrent();
            //float lastgcurrent = dlhl.getLastgcurrent();
            //报警逻辑
            // float lasta1current = dlhl.getLasta1current();
            // float lastb1current = dlhl.getLastb1current();
            // float lastc1current = dlhl.getLastc1current();
            // float lastd1current = dlhl.getLastd1current();
            //获取最大电流值
            float maxcurrentvalue = Math.max(lastacurrent, lastbcurrent);
            maxcurrentvalue = Math.max(maxcurrentvalue, lastccurrent);
            //获取最小电流值
            float mincurrentvalue = Math.min(lastacurrent, lastbcurrent);
            mincurrentvalue = Math.min(mincurrentvalue, lastccurrent);
            //不平衡系数
            float currnetcoefficient;
            if(maxcurrentvalue==0||mincurrentvalue==0){
                currnetcoefficient = 0;
            }
            else{
                currnetcoefficient = Float.isNaN(maxcurrentvalue / mincurrentvalue) ? 0f : (maxcurrentvalue / mincurrentvalue);
            }
            if(currnetcoefficient>=3)
            {
                if(maxcurrentvalue<=15)
                {
                    currnetcoefficient = 2.f;
                }
            }
            //电流比
            float acurrentpercentage;
            float bcurrentpercentage;
            float ccurrentpercentage;
            //如果母线电流小于5a则不计算
            if(lastdcurrent<=5f){
                //电流比置0 默认正常
                acurrentpercentage = 0f;
                bcurrentpercentage = 0f;
                ccurrentpercentage = 0f;
            }else{
                if(lastacurrent==0f){
                    acurrentpercentage=0f;
                }else{
                    acurrentpercentage = lastacurrent / lastdcurrent * 100;
                }
                if(lastbcurrent==0f){
                    bcurrentpercentage=0f;
                }else{
                    bcurrentpercentage = lastbcurrent / lastdcurrent * 100;
                }
                if(lastccurrent==0f){
                    ccurrentpercentage=0f;
                }else{
                    ccurrentpercentage = lastccurrent / lastdcurrent * 100;
                }
            }
            //定义电流报警状态值
            int acurrentstatus = GetAlarmStatus(lastacurrent, currentalarmvlaue, currentalarmrelievevlaue, currentwarnvlaue, currentwarnrelievevlaue, record.getLastaalarmstatus(), true, "A相电流", record.getDevicegroup(), record.getDeviceaddr(), record.getPointname());
            int bcurrentstatus = GetAlarmStatus(lastbcurrent, currentalarmvlaue, currentalarmrelievevlaue, currentwarnvlaue, currentwarnrelievevlaue, record.getLastbalarmstatus(), true, "B相电流", record.getDevicegroup(), record.getDeviceaddr(), record.getPointname());
            int ccurrentstatus = GetAlarmStatus(lastccurrent, currentalarmvlaue, currentalarmrelievevlaue, currentwarnvlaue, currentwarnrelievevlaue, record.getLastcalarmstatus(), true, "C相电流", record.getDevicegroup(), record.getDeviceaddr(), record.getPointname());
            //int gcurrentstatus = GetAlarmStatus(lastgcurrent, currentalarmvlaue, currentalarmrelievevlaue, currentwarnvlaue, currentwarnrelievevlaue, record.getLastgalarmstatus(), true, "接地电流", record.getDevicegroup(), record.getDeviceaddr(), record.getPointname());
            //定义电流比报警状态值
            int acurrentpercentagestatus = GetAlarmStatus(acurrentpercentage, currentpercentagealarmvlaue, currentpercentagealarmrelievevlaue, currentpercentagewarnvlaue, currentpercentagewarnrelievevlaue, record.getLastaralarmstatus(), true, "A相电流比", record.getDevicegroup(), record.getDeviceaddr(), record.getPointname());
            int bcurrentpercentagestatus = GetAlarmStatus(bcurrentpercentage, currentpercentagealarmvlaue, currentpercentagealarmrelievevlaue, currentpercentagewarnvlaue, currentpercentagewarnrelievevlaue, record.getLastbralarmstatus(), true, "B相电流比", record.getDevicegroup(), record.getDeviceaddr(), record.getPointname());
            int ccurrentpercentagestatus = GetAlarmStatus(ccurrentpercentage, currentpercentagealarmvlaue, currentpercentagealarmrelievevlaue, currentpercentagewarnvlaue, currentpercentagewarnrelievevlaue, record.getLastcralarmstatus(), true, "C相电流比", record.getDevicegroup(), record.getDeviceaddr(), record.getPointname());
            //定义三相不平衡系数报警值
            int currentcoefficientstatus = GetAlarmStatus(currnetcoefficient, coefficientalarmvlaue, coefficientalarmrelievevlaue, coefficientwarnvlaue, coefficientwarnrelievevlaue, record.getLastabcalarmstatus(), true, "三相不平衡系数", record.getDevicegroup(), record.getDeviceaddr(), record.getPointname());
    
            //设置报警状态
            dlhl.setLastaalarmstatus(acurrentstatus);
            dlhl.setLastbalarmstatus(bcurrentstatus);
            dlhl.setLastcalarmstatus(ccurrentstatus);
            //dlhl.setLastgalarmstatus(gcurrentstatus);
            dlhl.setLastaralarmstatus(acurrentpercentagestatus);
            dlhl.setLastbralarmstatus(bcurrentpercentagestatus);
            dlhl.setLastcralarmstatus(ccurrentpercentagestatus);
            dlhl.setLastabcalarmstatus(currentcoefficientstatus);
            //设置电流系数
            dlhl.setLastcoefficient(Float.isNaN(currnetcoefficient) ? 0f : currnetcoefficient);
            dlhl.setLastalarmmessage(GetAlarmMessage(acurrentstatus, "A相电流") +
                    GetAlarmMessage(bcurrentstatus, "B相电流") +
                    GetAlarmMessage(ccurrentstatus, "C相电流") +
                    //GetAlarmMessage(gcurrentstatus, "接地电流") +
                    GetAlarmMessage(acurrentpercentagestatus, "A相A/R") +
                    GetAlarmMessage(bcurrentpercentagestatus, "B相A/R") +
                    GetAlarmMessage(ccurrentpercentagestatus, "C相A/R") +
                    GetAlarmMessage(currentcoefficientstatus, "三相不平衡系数")
            );
            //获取最大电流值
            // float maxcurrent1value = Math.max(lasta1current, lastb1current);
            // maxcurrent1value = Math.max(maxcurrent1value, lastc1current);
            // //获取最小电流值
            // float mincurrent1value = Math.min(lasta1current, lastb1current);
            // mincurrent1value = Math.min(mincurrent1value, lastc1current);
            // //不平衡系数
            // float currnet1coefficient;
            // if(maxcurrent1value==0||mincurrent1value==0){
            //     currnet1coefficient = 0;
            // }else{
            //     currnet1coefficient = Float.isNaN(maxcurrent1value / mincurrent1value) ? 0f : (maxcurrent1value / mincurrent1value);
            // }
            // //电流比
            // float a1currentpercentage;
            // float b1currentpercentage;
            // float c1currentpercentage;
            // //判断母线电流,如果为0 则默认正常
            // if(lastd1current<=5f){
            //     a1currentpercentage = 0f;
            //     b1currentpercentage = 0f;
            //     c1currentpercentage = 0f;
            // }else{
            //     if(lasta1current==0f){
            //         a1currentpercentage=0f;
            //     }else{
            //         a1currentpercentage = lasta1current / lastd1current * 100;
            //     }
            //     if(lastb1current==0f){
            //         b1currentpercentage=0f;
            //     }else{
            //         b1currentpercentage = lastb1current / lastd1current * 100;
            //     }
            //     if(lastc1current==0f){
            //         c1currentpercentage=0f;
            //     }else{
            //         c1currentpercentage = lastc1current / lastd1current * 100;
            //     }
            // }
            //定义电流报警状态值
            //int a1currentstatus = GetAlarmStatus(lasta1current, currentalarmvlaue, currentalarmrelievevlaue, currentwarnvlaue, currentwarnrelievevlaue, record.getLasta1alarmstatus(), true, "A1相电流", record.getDeviceaddr(), record.getPointname());
           // int b1currentstatus = GetAlarmStatus(lastb1current, currentalarmvlaue, currentalarmrelievevlaue, currentwarnvlaue, currentwarnrelievevlaue, record.getLastb1alarmstatus(), true, "B1相电流", record.getDeviceaddr(), record.getPointname());
           // int c1currentstatus = GetAlarmStatus(lastc1current, currentalarmvlaue, currentalarmrelievevlaue, currentwarnvlaue, currentwarnrelievevlaue, record.getLastc1alarmstatus(), true, "C1相电流", record.getDeviceaddr(), record.getPointname());
            //定义电流比报警状态值
            //int a1currentpercentagestatus = GetAlarmStatus(a1currentpercentage, currentpercentagealarmvlaue, currentpercentagealarmrelievevlaue, currentpercentagewarnvlaue, currentpercentagewarnrelievevlaue, record.getLastar1alarmstatus(), true, "A1相电流比", record.getDeviceaddr(), record.getPointname());
            //int b1currentpercentagestatus = GetAlarmStatus(b1currentpercentage, currentpercentagealarmvlaue, currentpercentagealarmrelievevlaue, currentpercentagewarnvlaue, currentpercentagewarnrelievevlaue, record.getLastbr1alarmstatus(), true, "B1相电流比", record.getDeviceaddr(), record.getPointname());
            //int c1currentpercentagestatus = GetAlarmStatus(c1currentpercentage, currentpercentagealarmvlaue, currentpercentagealarmrelievevlaue, currentpercentagewarnvlaue, currentpercentagewarnrelievevlaue, record.getLastcr1alarmstatus(), true, "C1相电流比", record.getDeviceaddr(), record.getPointname());
            //定义三相不平衡系数报警值
           // int current1coefficientstatus = GetAlarmStatus(currnet1coefficient, coefficientalarmvlaue, coefficientalarmrelievevlaue, coefficientwarnvlaue, coefficientwarnrelievevlaue, record.getLastabc1alarmstatus(), true, "三相1不平衡系数", record.getDeviceaddr(), record.getPointname());
            //设置报警状态
            // dlhl.setLasta1alarmstatus(acurrentstatus);
            // dlhl.setLastb1alarmstatus(bcurrentstatus);
            // dlhl.setLastc1alarmstatus(ccurrentstatus);
            // dlhl.setLastar1alarmstatus(acurrentpercentagestatus);
            // dlhl.setLastbr1alarmstatus(bcurrentpercentagestatus);
            // dlhl.setLastcr1alarmstatus(ccurrentpercentagestatus);
            // dlhl.setLastabc1alarmstatus(currentcoefficientstatus);
            // //设置电流系数
            // dlhl.setLastcoefficient1(Float.isNaN(currnet1coefficient) ? 0f : currnet1coefficient);
            // dlhl.setLastalarmmessage(dlhl.getLastalarmmessage()+
            //         GetAlarmMessage(a1currentstatus, "A1相电流") +
            //         GetAlarmMessage(b1currentstatus, "B1相电流") +
            //         GetAlarmMessage(c1currentstatus, "C1相电流") +
            //         GetAlarmMessage(a1currentpercentagestatus, "A1相A/R") +
            //         GetAlarmMessage(b1currentpercentagestatus, "B1相A/R") +
            //         GetAlarmMessage(c1currentpercentagestatus, "C1相A/R") +
            //         GetAlarmMessage(current1coefficientstatus, "三相1不平衡系数")
            // );
            int[] status_arr = {dlhl.getLastaalarmstatus(), dlhl.getLastbalarmstatus(), dlhl.getLastcalarmstatus(), 
                dlhl.getLastaralarmstatus(), dlhl.getLastbralarmstatus(), dlhl.getLastcralarmstatus(),dlhl.getLastabcalarmstatus(),
               // dlhl.getLasta1alarmstatus(), dlhl.getLastb1alarmstatus(), dlhl.getLastc1alarmstatus(), 
               // dlhl.getLastar1alarmstatus(), dlhl.getLastbr1alarmstatus(), dlhl.getLastcr1alarmstatus(),dlhl.getLastabc1alarmstatus(),
            };
            dlhl.setStyle(record.getStyle());
            //设置总报警等级
            dlhl.setLastalarmlevel(MAX(status_arr));
            dlhl.setLastcommunicationstatus(0);
            dlhl.setLastdatatime(new Date());
            dlhl.setPointname(record.getPointname());
            dlhl.setLasthisdatatime(addHistory(record));
    
            if (dlhlsepsensorServiceImpl.Update(dlhl, false) == 0) {
                setText("更新实时数据失败，请检查数据库连接");
            }
        }
        private Date addHistory(Dlhlsepsensor sensor) {
            if (sensor != null) {
                if (sensor.getLasthisdatatime() == null) {
                    add(sensor);
                    return new Date();
                } else {
                    long lasttime = 0;
                    long nowtime = 0;
                    try {
                        lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                        nowtime = HexUtil.todate(new Date()).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    int timersp = 60000;
                    if (sensor.getLastalarmlevel() != 0) {
                        timersp = ad.getHisalarmtimersp()*1000;
                    } else {
                        timersp = ad.getHistimersp()*1000;
                    }
                    if (lasttime + timersp < nowtime) {
                        add(sensor);
                        return new Date();
                    }
                }
            }
            return null;
        }

        private void add(Dlhlsepsensor sensor) {
            Dlhlsephistory his = new Dlhlsephistory();
            his.setDeviceaddr(sensor.getDeviceaddr());
            his.setDevicegroup(sensor.getDevicegroup());
            his.setAlarmlevel(sensor.getLastalarmlevel());
            his.setAlarmmessage(sensor.getLastalarmmessage());
            his.setDatatime(sensor.getLastdatatime());
            his.setPointname(sensor.getPointname());
            his.setStationid(sensor.getStationid());
            //需要添加自己定义的属性
            his.setSignalpower(sensor.getLastsignalpower());
            his.setDcurrentaddr(sensor.getLastdcurrentaddr());
           // his.setA1current(sensor.getLasta1current());
            his.setAcurrent(sensor.getLastacurrent());
            //his.setB1current(sensor.getLastb1current());
            his.setBcurrent(sensor.getLastbcurrent());
            //his.setC1current(sensor.getLastc1current());
            his.setCcurrent(sensor.getLastccurrent());
            his.setCoefficient(sensor.getLastcoefficient());
            //his.setCoefficient1(sensor.getLastcoefficient1());
            //his.setD1current(sensor.getLastd1current());
            his.setDcurrent(sensor.getLastdcurrent());
            //his.setGcurrent(sensor.getLastgcurrent());
            his.setAalarmstatus(sensor.getLastaalarmstatus());
            his.setBalarmstatus(sensor.getLastbalarmstatus());
            his.setCalarmstatus(sensor.getLastcalarmstatus());
            his.setGalarmstatus(sensor.getLastgalarmstatus());
            //his.setA1alarmstatus(sensor.getLasta1alarmstatus());
            //his.setB1alarmstatus(sensor.getLastb1alarmstatus());
           // his.setC1alarmstatus(sensor.getLastc1alarmstatus());
            dlhlsepsensorServiceImpl.Add(his);
        }
    /**
     * 判断电流大小并与系数计算返回校正后的电流
     *
     * @param current
     * @param greateValue
     * @param lessValue
     * @return
     */
    public float getCurrent(float current, float greateValue, float lessValue) {
        float value = current;
        if (current >= 10) {
            value =  current * greateValue;
        } else if (current < 10) {
            value =  current * lessValue;
        }
        return Float.isNaN(value)?0f:value;
    }
    private Float getDcurrent(float current, float greateValue, float lessValue) {
        float value = current;
        if (current >= 180) {
            value =  current * greateValue;
        } else if (current < 180) {
            value =  current * lessValue;
        }
        return Float.isNaN(value)?0f:value;
    }

        @Async("threadPool")
        public void startSendThread(Appdevice Appdevice) throws Exception {
            checkType = "crc16";
            issend.put(Thread.currentThread().getId(), true);
            String cstr = "";
            String cmdtype = "";
            String nametype = "";
            int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
            while (issend.get(Thread.currentThread().getId()) != null) {
                if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                    addrindex = Appdevice.getAddrmin();
                    // if(addrid>=ssList.size())
                    // {
                    //     addrid=0;
                    // }

                cstr = String.format(Appdevice.getCmd(), String.format("%02X", addrindex));
                cstr = cstr + CRC16.calcCrc16(cstr);
                try {
                    if (ad.getCommunicationmode() == 2)
                    Send(cstr);
                    else if(ad.getCommunicationmode() == 3)
                    if(ssList.size()>0)
                    {
                        for(int i=0;i<ssList.size();i++)
                        {
                            if(ssList.get(i).isConnected()&&!ssList.get(i).isClosed())
                            Sendtcp(cstr,ssList.get(i));
                            else
                            {
                            ssList.remove(i);   
                            //skaddrList.remove(addrid);                          
                            }  
                            Thread.sleep(20);  
                           // addrid ++;                        
                        }
                    }
                } catch (Exception EX) {
                     setText(EX.toString());
                     //ssList.remove(addrid);     
                }
                setText("向"+ ssList.size()+ Appdevice.getName() + "设备发送指令" + cstr);
                reSend[addrindex]++;
                if (reSend[addrindex] > Appdevice.getAddrmax()) {
                dlhlsepsensorServiceImpl.UpdateStatus(ad, addrindex,1);
                reSend[addrindex] = 0;
                //addrindex++;
                }

                Thread.sleep(timersp);
                if(addrindex==Appdevice.getAddrmax())
                Thread.sleep(60*1000);
                addrindex++;
                
            }
        }

        // @Async("threadPool")
        // public void startReceiveThread(){
        //     isrecv.put(Thread.currentThread().getId(), true);
        //     while (isrecv.get(Thread.currentThread().getId()) != null) {
        //         //这里根据实际协议替换,解析方法recvCrc16;recvSum();
        //         recv();
        //         try {
        //             Thread.sleep(interval);
        //         } catch (InterruptedException e) {
        //             e.printStackTrace();
        //         }
        //     }
        // }
}
